import 'dart:convert';

import 'package:chi_med_det_flutter/userinfo.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;
import 'package:chi_med_det_flutter/url.dart';

enum ItemType {
  MODIFY_PERSONAL_INFO,
  USER_FEED_BACK,
  PRIVACY_DESCRIPTION,
  ABOUT,
  LOGOUT,
}

class Personal extends StatefulWidget {
  const Personal({super.key});

  @override
  State<StatefulWidget> createState() => _PersonalSate();
}

class _PersonalSate extends State<Personal> {
  final _pressStateMap = <ItemType, bool>{};
  final _feedbackController = TextEditingController();

  void showSnakeBar(String content) {
    final snackBar = SnackBar(
      content: Text(content),
      duration: Duration(seconds: 3),
      action: SnackBarAction(label: "知道了", onPressed: () {}),
    );
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  void logout() {
    Navigator.pushNamed(context, '/login');
    final UserInfo userInfo = Provider.of<UserInfo>(context);
    userInfo.setAccount("");
  }

  Widget makePersonalItem(ItemType itemType, String title) {
    return FractionallySizedBox(
      widthFactor: .8,
      child: InkWell(
        onTapDown: (_) {
          setState(() {
            _pressStateMap[itemType] = true;
          });
        },
        onTapUp: (_) {
          setState(() {
            _pressStateMap[itemType] = false;
          });
          switch (itemType) {
            case ItemType.MODIFY_PERSONAL_INFO:
              showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: Text("修改个人信息"),
                    content: Text("功能尚未完善，敬请期待"),
                  );
                },
              );
              break;
            case ItemType.USER_FEED_BACK:
              showDialog(
                context: context,
                barrierDismissible: false,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: Text("用户反馈"),
                    content: TextField(
                      controller: _feedbackController,
                      maxLines: 1,
                      maxLength: 30,
                      decoration: InputDecoration(hintText: "请输入反馈信息"),
                    ),
                    actions: [
                      TextButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: Text("取消"),
                      ),

                      TextButton(
                        onPressed: () {
                          var content = _feedbackController.text.trim();
                          if (content.isNotEmpty) {
                            final url = Uri.parse(URL.FEEDBACK);
                            final UserInfo userInfo = Provider.of<UserInfo>(
                              context,
                              listen: false,
                            );
                            http.post(
                                  url,
                                  headers: const {
                                    'Content-Type': 'application/json',
                                  },
                                  body: jsonEncode({
                                    'account': userInfo.getAccount(),
                                    'content': content,
                                  }),
                                )
                                .then((value) {})
                                .catchError((err) {});
                            showSnakeBar("感谢您的反馈");
                          }
                          Navigator.of(context).pop();
                        },
                        child: Text(
                          "确定",
                          style: TextStyle(
                            color: Colors.deepPurple,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ],
                  );
                },
              );
              break;
            case ItemType.PRIVACY_DESCRIPTION:
              showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: Text("隐私保护说明"),
                    content: Text("您的数据仅被用于当次体质检测，不会发生存储及转移行为"),
                  );
                },
              );
              break;
            case ItemType.ABOUT:
              PackageInfo.fromPlatform()
                  .then((PackageInfo packageInfo) {
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: Text("关于"),
                          content: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text("软件名称: ${packageInfo.appName}"),
                              Text("软件版本: ${packageInfo.version}"),
                              Text("构建序号: ${packageInfo.buildNumber}"),
                            ],
                          ),
                        );
                      },
                    );
                  })
                  .catchError((err) {
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return AlertDialog(title: Text("获取版本信息失败，请稍后重试"));
                      },
                    );
                  });
              break;
            case ItemType.LOGOUT:
              logout();
              break;
          }
        },
        onTapCancel: () {
          setState(() {
            _pressStateMap[itemType] = false;
          });
        },
        child: Container(
          padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(5)),
            border: Border.all(
              color:
                  (_pressStateMap[itemType]) ?? false
                      ? Colors.grey
                      : Colors.deepPurpleAccent,
              width: 2,
            ),
          ),
          child: Text(
            title,
            style: TextStyle(fontSize: 20),
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final UserInfo userInfo = Provider.of<UserInfo>(context);
    final String account = userInfo.getAccount();
    return Center(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(height: 8),
          CircleAvatar(
            radius: 60,
            backgroundImage: AssetImage('assets/images/avatar.jpg'),
          ),
          SizedBox(height: 5),
          Text(
            account,
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          Expanded(
            child: ListView(
              children: [
                SizedBox(height: 20),
                makePersonalItem(ItemType.MODIFY_PERSONAL_INFO, "修改个人信息"),
                SizedBox(height: 20),
                makePersonalItem(ItemType.USER_FEED_BACK, "用户反馈"),
                SizedBox(height: 20),
                makePersonalItem(ItemType.PRIVACY_DESCRIPTION, "隐私保护说明"),
                SizedBox(height: 20),
                makePersonalItem(ItemType.ABOUT, "关于"),
                SizedBox(height: 20),
                makePersonalItem(ItemType.LOGOUT, "退出登录"),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
